package com.example.a2205douyin.live;

import android.content.Context;
import android.os.Handler;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;

import com.blankj.utilcode.util.SPUtils;
import com.example.a2205douyin.R;
import com.example.a2205douyin.entity.GiftEntity;

import java.util.Timer;
import java.util.TimerTask;

public class GiftControl {
    private GiftLayout giftLayout;
    private Context context;
    private Timer timer;
    private Handler handler = new Handler(){};
    private int count = 0;//用来记录礼物发送的数量
    private long lastTime;//用来记录礼物发送的时间

    public GiftControl(GiftLayout giftLayout, Context context) {
        this.giftLayout = giftLayout;
        this.context = context;
        timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                if(System.currentTimeMillis()-lastTime>3000){//两次时间差超过3秒，暴击效果消失
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            giftLayout.setVisibility(View.GONE);
                            count = 0;
                        }
                    });
                }
            }
        },0,100);
    }

    public void load(GiftEntity.DataBean dataBean){
        //第一次发送礼物时，需要将暴击效果设为显示，第二次点击不超过2秒时，暴击效果并不会消失，所以不需要再次显示
        if(count==0){
            count++;
            showGiftLayout();//暴击效果显示
            lastTime = System.currentTimeMillis();//更新礼物发送时间
        } else if (System.currentTimeMillis()-lastTime<2000) {
            count++;
            lastTime = System.currentTimeMillis();//更新礼物发送时间
        }
        giftLayout.loadGift(dataBean);
        giftLayout.loadIcon(SPUtils.getInstance().getString("icon"));
        giftLayout.loadName(SPUtils.getInstance().getString("username"));
        giftLayout.loadCount(count);
    }

    private void showGiftLayout() {
        giftLayout.setVisibility(View.VISIBLE);
        Animation animation = AnimationUtils.loadAnimation(context, R.anim.gift_in);
        giftLayout.startAnimation(animation);
    }
}
